var viewUserModel = new function () {
    this.ItemList = ko.observableArray(data.ItemList);
    this.PageSize = ko.observable(data.PageSize);
    this.PageIndex = ko.observable(data.PageIndex == null || data.PageIndex == 0 ? 0 : 1);
    this.TotalPage = ko.observable(data.TotalPage);
    this.TotalRecord = ko.observable(data.TotalRecord);

    // Messages
    this.PageText = ko.computed(function () {
        var total = this.TotalRecord();
        return total + " danh mục";
    }, this);

    this.PageSizeText = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);
        if (!IsNumeric(pagevalue))
            return "* Nhập một số giữa 1 - 100";
        else if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return "* Nhập một số giữa 1 - 100";
        }
        else {
            return "";
        }
    }, this);
    this.PageIndexText = ko.computed(function () {
        var pagevalue = this.PageIndex().toString().replace(/\s/g, '');
        var pageindex = parseInt(pagevalue, 10);

        if (this.TotalRecord().length != 0) {
            if (!IsNumeric(pagevalue) || pagevalue == "" || pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.TotalPage()) {
                return "* Nhập một số giữa 1 - " + this.TotalPage() + " ";
            }
            else {
                return "";
            }
        }
        return "";

    }, this);

    this.SetOrder = SetOrder;
    this.ColumnName = ko.observable("Title");
    this.SortOrder = ko.observable("asc");

    // Prev buttons
    this.PrevButton = function () {
        if (viewUserModel.PageIndex() - 1 > 0) {
            viewUserModel.PageIndex(viewUserModel.PageIndex() - 1);
            FilterData($('#q').val());
        }
    };
    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.PageIndex());
        if (page > 1) {
            return "btn btn-prev-arrow prev-active";
        }
        else {
            return "btn btn-prev-arrow";
        }
    }, this);

    // Next buttons
    this.NextButton = function () {
        if (viewUserModel.PageIndex() + 1 <= viewUserModel.TotalPage()) {
            viewUserModel.PageIndex(viewUserModel.PageIndex() + 1);
            FilterData($('#q').val());
        }
    };

    this.NextButtonClass = ko.computed(function () {
        if (this.PageIndex() == this.TotalPage() || this.TotalPage() == 1)
            return "btn btn-next-arrow next-disabled";
        else
            return "btn btn-next-arrow";
    }, this);

    // Search
    this.SearchButton = function () {
        var keywords = $('#q').val();
        FilterData(keywords);
    };
    this.RunSomethingKey = function (viewUserModel, event) {
        if (event.keyCode == 13 || event.keyCode == 9) {
            this.RunSomething(viewUserModel, event);
        }
        return true;
    }
    this.RunSomething = function (viewUserModel, event) {
        var keywords = $('#q').val();
        FilterData(keywords);
    }

    // Sort 
    function SwitchSortOrder() {
        if (viewUserModel.SortOrder() === "asc") {
            viewUserModel.SortOrder("desc");
        } else {
            viewUserModel.SortOrder("asc");
        }
    }
    function SetOrder(event, ColumnName) {
        if (viewUserModel.ColumnName() === ColumnName) {
            SwitchSortOrder();
        }
        else {
            viewUserModel.ColumnName(ColumnName);
            viewUserModel.SortOrder("desc");
        }
        SetTHClass(event, ColumnName);
    }
    this.SetOrder = SetOrder;

    function SetTHClass(event, ColumnName) {
        //remove the existing classes
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");

        if (viewUserModel.SortOrder() === "asc") {
            $("#" + ColumnName + " span").addClass("asc");

        } else {
            $("#" + ColumnName + " span").addClass("desc");
        }

        // Load data
        FilterData($('#q').val());
    }

    // Common function here
    // Edit function
    this.ItemId = ko.observable(0);
    this.ItemTitle = ko.observable("");
    this.DeleteItems = function (item) {
        viewUserModel.ItemId(item.StatusId);
        viewUserModel.ItemTitle(item.Title);
        $('#fancybox-overlay').show();
        $('#popupDelete').showPopup({
            width: 420
        });
    };

    // Delete
    this.Delete = function () {
        openProcess();
        var dataPost = { "id": this.ItemId() };
        $.ajax({
            type: "POST",
            url: "/User/Delete",
            data: dataPost,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                // Stop progress bar
                hideProcess();

                // Set values
                viewUserModel.PageIndex(data.TotalRecord == 0 ? 0 : data.PageIndex);
                viewUserModel.TotalPage(data.TotalPage);
                viewUserModel.PageSize(data.PageSize);
                viewUserModel.TotalRecord(data.TotalRecord);
                viewUserModel.ItemList(data.ItemList == null ? [] : data.ItemList);
            },
            error: function (xhr, status, error) {
                // Stop progress bar
                hideProcess();
                showPopupError();
            }
        });
    };

    // Filter items
    function FilterData(keywords) {
        // Send a request to controller via Ajax call
        // Get back value an set it to view
        // Using knockout to wrap data returned
        if (keywords != undefined && keywords.toLowerCase() == "từ khóa")
            keywords = "";
        openProcess();
        var dataPost = {
            "keywords": keywords,
            "sortBy": viewUserModel.ColumnName(),
            "SortOrder": viewUserModel.SortOrder(),
            "pageIndex": viewUserModel.PageIndex(),
            "pageSize": viewUserModel.PageSize()
        };
        $.ajax({
            type: "POST",
            url: "/User/Filters",
            data: dataPost,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                // Stop progress
                hideProcess();

                // Set values
                viewUserModel.PageIndex(data.TotalRecord == 0 ? 0 : data.PageIndex);
                viewUserModel.TotalPage(data.TotalPage);
                viewUserModel.PageSize(data.PageSize);
                viewUserModel.TotalRecord(data.TotalRecord);
                viewUserModel.ItemList(data.ItemList == null ? [] : data.ItemList);
            },
            error: function (xhr, status, error) {
                // Stop progress bar
                hideProcess();
                showPopupError();
            }
        });
    }

    // Call object refresh data
    this.RefreshDataByPageSize = function () {
        FilterData("");
    };
    this.RefreshDataByPageIndex = function () {
        FilterData("");
    };
}

ko.applyBindings(viewUserModel, document.getElementById("main"));

$(document).ready(function () {
    $('#PageSize').removeClass('text-active');
    $('#PageIndex').removeClass('text-active');
    $('#PageSize').data('lastValue', $('#PageSize').val());
    $('#PageIndex').data('lastValue', $('#PageIndex').val());

    // Key down, handle only for IE
    $('#PageSize').live('keydown', function (e) {
        var keyCode = e.keyCode || e.which;
        if (is_ie && keyCode == 13) {
            var lastValue = $('#PageSize').data('lastValue');
            var currentvalue = $('#PageSize').val().toString().replace(/\s/g, '');

            if (currentvalue != lastValue && lastValue != undefined) {
                var PageSize = parseInt(currentvalue, 10);

                if (!IsNumeric(currentvalue) || PageSize.toString() == 'NaN' || PageSize < 1 || PageSize > 100) {
                }
                else {
                    $('#PageSize').data('lastValue', currentvalue);
                    $('#PageIndex').val("1");

                    e.preventDefault();
                    viewUserModel.RefreshDataByPageSize();

                    return false;
                }
            }
            else {
                $('#PageSize').data('lastValue', currentvalue);
            }
        }
    });
    $('#PageIndex').live('keydown', function (e) {
        var keyCode = e.keyCode || e.which;

        if (is_ie && keyCode == 13) {
            var lastValue = $('#PageIndex').data('lastValue');
            var currentvalue = $('#PageIndex').val().toString().replace(/\s/g, '');
            var pageindex = parseInt(currentvalue, 10);

            if (currentvalue != lastValue && lastValue != undefined) {
                if (!IsNumeric(currentvalue) || currentvalue == "" || currentvalue.toString() == 'NaN' || !IsNumeric(currentvalue) || pageindex < 1 || pageindex > viewUserModel.TotalPage()) {
                }
                else {
                    $('#PageIndex').data('lastValue', currentvalue);
                    e.preventDefault();
                    viewUserModel.RefreshDataByPageIndex();
                }
            }
            else {
                $('#PageIndex').data('lastValue', currentvalue);
            }
        }
    });


    // Handle input tag blur
    $('#PageSize').change(function (e) {
        var lastValue = $('#PageSize').data('lastValue');
        var pagevalue = $('#PageSize').val().toString().replace(/\s/g, '');
        var PageSize = parseInt(pagevalue, 10);

        if (lastValue != pagevalue) {
            if (!IsNumeric(pagevalue) || PageSize.toString() == 'NaN' || PageSize < 1 || PageSize > 100) {
            }
            else {
                $('#PageSize').data('lastValue', pagevalue);
                $('#PageIndex').val("1");
                e.preventDefault();
                viewUserModel.PageIndex(1);
                viewUserModel.RefreshDataByPageSize();
            }
        }
        else {
            $('#PageSize').data('lastValue', pagevalue);
        }
    });

    $('#PageIndex').change(function (e) {
        var lastValue = $('#PageIndex').data('lastValue');
        var pagevalue = $('#PageIndex').val().toString().replace(/\s/g, '');
        var pageindex = parseInt(pagevalue, 10);

        if (lastValue != pagevalue) {
            if (!IsNumeric(pagevalue) || pagevalue == "") {
            }
            else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > viewUserModel.TotalPage()) {
            }
            else {
                $('#PageIndex').data('lastValue', pagevalue);
                e.preventDefault();
                viewUserModel.RefreshDataByPageIndex();
            }
        }
        else {
            $('#PageIndex').data('lastValue', pagevalue);
        }
    });
});
